package creator.singleton;

/**
 * 单例模式实例
 */
public class SingletonDemo {

    // 1. 懒汉式 单线程
    private static SingletonDemo instance = null;

    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() {
        if (instance == null) {
            instance = new SingletonDemo();
        }
        return instance;
    }

    // 2. 饿汉式 单线程

    private static SingletonDemo instance2 = new SingletonDemo();

    public static SingletonDemo getInstance2() {
        return instance2;
    }

    // 3. 懒汉式线程安全
    private static SingletonDemo instance3 = null;

    public static synchronized SingletonDemo getInstance3() {
        if (instance3 == null) {
            instance3 = new SingletonDemo();
        }
        return instance3;
    }

    // 4. 饿汉式线程安全
    private static SingletonDemo instance4 = new SingletonDemo();

    public static synchronized SingletonDemo getInstance4() {
        return instance4;
    }

    // 5. 懒汉式线程安全，双重检查锁定
    private volatile static SingletonDemo instance5 = null;

    public static SingletonDemo getInstance5() {
        if (instance5 == null) {
            synchronized (SingletonDemo.class) {
                if (instance5 == null) {
                    instance5 = new SingletonDemo();
                }
            }
        }
        return instance5;
    }

    // 6. 饿汉式线程安全，双重检查锁定
    private  volatile static SingletonDemo instance6 = new SingletonDemo();

    public static SingletonDemo getInstance6() {
        return instance6;
    }

    // 7. 静态内部类

    private static class SingletonHolder {
        private static final SingletonDemo INSTANCE = new SingletonDemo();
    }

    public static SingletonDemo getInstance7() {
        return SingletonHolder.INSTANCE;
    }

    // 8. 枚举

    public enum SingletonEnum {
        INSTANCE;

        public void whateverMethod() {
            // do something
        }
    }


}
